from sqlmodel import SQLModel
import inspect
from datetime import datetime
from typing import List, Dict, Union
from enum import Enum
from sqlmodel.ext.asyncio.session import AsyncSession

def format_timestamp(timestamp: int) -> str:
    """将时间戳转换为格式化的日期时间字符串"""
    return datetime.fromtimestamp(timestamp).strftime('%Y-%m-%d %H:%M:%S')

# 查询类的所有字段 包含父类的字段
def get_all_model_fields(model_class):
    fields = {}
    # 遍历类的继承树（包括父类）
    for cls in inspect.getmro(model_class):
        if issubclass(cls, SQLModel):
            fields.update(cls.__annotations__)
    return fields

def process_enums(data: Union[Dict, List], model_instance=None) -> Union[Dict, List]:
    """
    递归处理字典或列表中的所有枚举字段，并通过模型实例的 @property 获取对应的文本表示字段。
    :param data: 输入的数据（字典或列表）。
    :param model_instance: 当前处理的模型实例，用于获取字段的文本表示。
    :return: 处理后的数据（字典或列表）。
    """
    if isinstance(data, dict):
        new_data = {}
        model_class = model_instance.__class__ if model_instance else None
        fields = get_all_model_fields(model_class) if model_class else {}

        for key, value in data.items():
            # 如果字段是 SQLModel 实例，递归处理其字段
            if isinstance(value, SQLModel):
                value = process_enums(value.dict(), value)
            elif isinstance(value, dict):
                # 如果字段是字典，递归处理
                value = process_enums(value, model_instance)
            elif isinstance(value, list):
                # 如果字段是列表，递归处理列表中的每个元素
                value = [process_enums(item, model_instance) for item in value]

            # 处理枚举字段的文本表示，通过模型实例获取文本值
            if key in fields:
                field_type = fields[key]
                if isinstance(field_type, type) and issubclass(field_type, Enum):
                    text_field_name = f"{key}_text"
                    if model_instance and hasattr(model_instance, text_field_name):
                        # 获取该模型实例的 text_field_name 值
                        new_data[text_field_name] = getattr(model_instance, text_field_name)
            
            new_data[key] = value

        # 单独处理最外层模型实例的枚举字段
        if model_instance:
            for key, field_type in fields.items():
                if isinstance(field_type, type) and issubclass(field_type, Enum):
                    text_field_name = f"{key}_text"
                    if hasattr(model_instance, text_field_name):
                        new_data[text_field_name] = getattr(model_instance, text_field_name)

        return new_data
    elif isinstance(data, list):
        # 处理列表中的每个元素
        return [process_enums(item, model_instance) for item in data]
    return data



def process_timestamps(data: Union[Dict, List]) -> Union[Dict, List]:
    """递归处理字典或列表中的所有时间戳字段"""
    if isinstance(data, dict):
        new_data = {}
        for key, value in data.items():
          
            if isinstance(value, SQLModel):
                # 将 SQLModel 实例转换为字典
                value = value.dict()
            if isinstance(value, dict):
                # 递归处理子字典
                new_data[key] = process_timestamps(value)
            elif isinstance(value, list):
                # 递归处理列表
                new_data[key] = [process_timestamps(item) for item in value]
            elif isinstance(value, int) and key.endswith('time'):
                # 如果是时间戳字段，添加格式化的时间
                new_data[key] = value
                new_data[f"{key}_formatted"] = format_timestamp(value)
            else:
                # 直接复制非时间戳字段
                new_data[key] = value
        return new_data
    elif isinstance(data, list):
        # 处理列表中的每个元素
        return [process_timestamps(item) for item in data]
    return data
